# -*- coding: utf8 -*-
import re
import common

site_index = 'utamap'
site_keyword = 'utamap'
site_url = 'http://www.utamap.com/'
test_url = 'http://www.utamap.com/showkasi.php?surl=70380'

def get_lyric(url):
    prefix = 'http://www.utamap.com/phpflash/flashfalsephp.php?unum='
    pattern = 'surl=([^&=]+)'

    bool = re.compile(pattern).search(url)

    if bool:
        id = bool.group(1)
        full_url = prefix + id
        
        # get data
        data = common.get_url_content(full_url)

        lyric = unicode(data, 'utf8')

        front_str = 'test2='
        start = lyric.find(front_str) + len(front_str)
        lyric = lyric[start:]
        lyric = lyric.strip()

        # test for half to full
        lyric = common.half2full(lyric)

        song_info = _get_song_info(url)
        lyric = song_info + lyric

        return lyric

    return None

def _get_song_info(url):
    data = common.get_url_content(url)

    encoding = 'sjis'
    data = data.decode(encoding, 'ignore')

    lines = []

    # title, artist, sakusi, sakyoku
    pattern = '\n'.join([
        '<INPUT type="hidden" name=title value="([^"]*)">',
        '<INPUT type="hidden" name=artist value="([^"]*)">',
        '<INPUT type="hidden" name=sakusi value="([^"]*)">',
        '<INPUT type="hidden" name=sakyoku value="([^"]*)">',
    ])
    regex = re.compile(pattern).search(data)
    if regex:
        title = regex.group(1)
        artist = regex.group(2)
        sakusi = regex.group(3)
        sakyoku = regex.group(4)

    lines.append(u'%s\n' % (title))
    lines.append(u'作詞：%s' % (sakusi))
    lines.append(u'作曲：%s' % (sakyoku))
    lines.append(u'唄：%s' % (artist))

    lines.append('\n\n')

    string = '\n'.join(lines)

    return string

